package org.streets.extention.quartz;

import java.text.ParseException;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
/**
 * 
 * @author dzb
 *
 */
public class QuartzScheduler {	
	
	private final String group;
	private final Scheduler scheduler;
			
	public QuartzScheduler(Scheduler scheduler, String group) {
		this.group = group;
		this.scheduler = scheduler;
	}
	
	public void scheduleJob(QuartzJob job) {
		Class<?> clzz = job.getType();
		String groupName = job.getGroup();
		JobDetail jobDetail = new JobDetail("job."+job.getName(), groupName, clzz);
		CronTrigger trigger;
		try {
			trigger = new CronTrigger("trigger."+job.getName(), 
					groupName, job.getExpression());
			scheduler.scheduleJob(jobDetail, trigger);

		} catch (ParseException e) {
			throw new QuartzSchedulerException(job.getName()+"'s Cron Express["+job.getExpression()+"] error", e);			
		} catch (SchedulerException e) {
			throw new QuartzSchedulerException("Can not schedule Job "+job.getName());
		}				
	}
	
	public void start() {
		try {
			scheduler.start();
		} catch (SchedulerException e) {
			throw new QuartzSchedulerException("start job error!", e);			
		}
	}

	public void pauseAll() {
		try {
			scheduler.pauseAll();
		} catch (SchedulerException e) {			
			throw new QuartzSchedulerException("Pause All job error!", e);			
		}
	}
	
	public void pauseJob(String jobId) {
		try {
			scheduler.pauseJob(jobId, group);
		} catch (SchedulerException e) {
			throw new QuartzSchedulerException("Pause job["+group+"."+jobId+"] error!", e);			
		}
	}
	
	public void resumeJob(String jobId) {
		try {
			scheduler.resumeJob(jobId, group);
		} catch (SchedulerException e) {
			throw new QuartzSchedulerException("Resume job["+group+"."+jobId+"] error!", e);
		}
	}
	
	public void removeJob(String jobId) {
		try {
			scheduler.deleteJob(jobId, group);
		} catch (SchedulerException e) {
			throw new QuartzSchedulerException("Remove job["+group+"."+jobId+"] error!", e);
		}		
	}
	
}
